iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
2

本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (16) 建立會員系統 - 5

1. 修改登入後的顯示

在專案WebMvc的Views/Shaered修改_Layout.cshtml和新增_LoginPartial.cshtml,判斷是否登入而顯示名字或者Logout按鈕。

_Layout.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebMvc</title>
    <link rel="stylesheet" href="~/css/site.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Press+Start+2P"
          rel="stylesheet" />
    <link href="https://unpkg.com/nes.css@2.3.0/css/nes.min.css"
          rel="stylesheet" />
</head>
<body>
    <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button"
                        class="navbar-toggle"
                        data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Catalog" asp-action="Index">
                    <strong>RPG</strong> Shop
                </a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    @await Html.PartialAsync("_LoginPartial")
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
    </nav>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>


    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

_LoginPartial.cshtml

@using Microsoft.AspNetCore.Identity

@if (User?.Identity?.IsAuthenticated == true)
{
    <li>
        @User.FindFirst(x => x.Type == "preferred_username").Value
    </li>
    <li class="pull-right">
        <form asp-area="" asp-controller="Account" asp-action="SignOut" method="post" id="logoutForm">
            <a href="javascript:document.getElementById('logoutForm').submit()">
                Log Out
            </a>
        </form>
    </li>
}
else
{
    <li>
        <a asp-area="" asp-controller="Account" asp-action="SignIn">
            Login
        </a>
    </li>
}

2. 新增AccountController

在專案WebMvc的Controllers新增AccountController,包含登入和登出的功能

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;

namespace WebMvc.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        public async Task<IActionResult> SignIn(string returnUrl)
        {
            var user = User as ClaimsPrincipal;
            var token = await HttpContext.GetTokenAsync("access_token");
            var idToken = await HttpContext.GetTokenAsync("id_token");
            foreach(var claim in user.Claims)
            {
                Debug.WriteLine($"Claim Type: {claim.Type} - Claim Value : {claim.Value}");
            }

            if(token != null)
            {
                ViewData["access_token"] = token;
            }

            if(idToken != null)
            {
                ViewData["id_token"] = idToken;
            }

            return RedirectToAction(nameof(CatalogController.About), "Catalog");
        }

        public async Task<IActionResult> Signout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

            var homeUrl = Url.Action(nameof(CatalogController.Index), "Catalog");
            return new SignOutResult(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = homeUrl });
        }
    }
}

-------------------------------------

放假的進度比較慢,預計明天能寫Docker的版本QQ


上一篇
[Day15] 建立會員系統 - 4
下一篇
[Day17] 建立會員系統 - 6
系列文
一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言